package com.gold.security;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.gold.common.JsonUtils;
import com.gold.common.TokenUtil;
import com.gold.entity.User;
import org.codehaus.jackson.node.JsonNodeFactory;
import org.codehaus.jackson.node.ObjectNode;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

/**登录成功自定义
 * @author XiaoHao
 * @date 2022-05-07 16:04
 */
public class AuthSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json;charset=utf-8");

        JSONObject jsonObject = new JSONObject();
        //登录成功后的用户角色
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        StringBuilder sb = new StringBuilder();
        for (GrantedAuthority authority : authorities) {
            sb.append(authority.getAuthority());
            sb.append(",");
        }
        //将用户和角色放入token中
        jsonObject.put("Token", TokenUtil.getToken(authentication.getName(),sb.toString()));
        User user = (User)authentication.getDetails();
        jsonObject.put("uuId",user.getWechatLogin().getWxId());
        PrintWriter out = response.getWriter();
        out.write(JsonUtils.responseJson(true,200,"登录成功",jsonObject).toJSONString());
        out.flush();
        out.close();
    }


}
